<!--目前仅支持单列下拉-->
<template>
  <div style="width: 100%">
    <vxe-pulldown ref="xDown" :transfer="true" style="width: 100%;" @hide-panel="hidePanel">
      <template v-slot>
        <div @mouseover="mouseover" @mouseout="mouseout">
          <vxe-input v-model="localValue" :suffix-icon="suffixIcon" :placeholder="$attrs.placeholder" ref="pan"
                     @chage="inputChange" style="width: 100%" @blur="blurEvent" readonly size="small"
                     @focus="focusEvent" @suffix-click="suffixClick"></vxe-input>
        </div>
      </template>
      <template v-slot:dropdown>
        <div class="my-dropdown" ref="dropdown">
          <div style="margin-right: 10px">
            <vxe-input v-model="searchValue" @change="searchValueChange" style="width: 100%;" ref="searchValue" clearable></vxe-input>
            <div style="text-align: center; margin: 10px 0" v-if="multiple">
              <vxe-button size="medium" content="全选" @click="allClick"></vxe-button>
              <vxe-button size="medium" content="取消全选" @click="cancelClick"></vxe-button>
            </div>
          </div>
          <div style="max-height: 200px; overflow-y: auto">
            <vxe-grid
                ref="xGrid"
                :keyboard-config="keyboardConfig"
                class="tableClass"
                highlight-current-row
                highlight-hover-row
                max-height="200px"
                show-overflow="title"
                :row-style="rowStyle"
                :align="showHeader ? 'center' : 'left'"
                header-align="center"
                :show-header="showHeader"
                border="none"
                :loading="loading4"
                :data="tableData"
                :columns="tableColumn"
                @cell-click="cellClickEvent">
            </vxe-grid>
          </div>
          <v-pager @sizeChange="sizeChange" :pageSize="pagerValue.pageSize" v-if="showPager"
                   :total="pagerValue.total" :customPage="pagerValue.customPage"
                   @jumpPage="jumpPage"
                   style="margin-right: 10px">
          </v-pager>
        </div>
      </template>
    </vxe-pulldown>
  </div>
</template>

<script>
import projectModuleApi from '@/api/projectModuleApi.js'
import VPager from "./vPager";
export default {
  name: "vSelectTablePage",
  components: {
    VPager
  },
  mounted() {
    // console.log(this.$refs.xGrid);
    // this.$el.addEventListener('keyup', this.enterSelect)
  },
  destroyed() {
    // this.$el.removeEventListener('keyup', this.enterSelect)
  },
  props: {
    options: {
      type: Array,
      default: function () {
        return undefined
      }
    },
    value: {
      type: [String, Number, Array],
      default: function () {
        return undefined
      }
    },
    column: {
      type: [Array, Object, String],
      default: function () {
        return undefined
      }
    },
    multiple : {
      type: Boolean,
      default: function () {
        return false
      }
    },
    showHeader: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    clickValue: {
      type: [String, Array],
      default: function () {
        return 'Id'
      }
    },
    queryValue: {
      type: Object,
      default: function () {
        return {
          // id: this.$route.params.id,
        }
      }
    },
    api: {
      type: Object,
      default: function () {
        return undefined
      }
    },
    getPage: {
      type: String,
      default: function () {
        return 'getPage'
      }
    },
    showValue: {
      type: String,
      default: function () {
        return undefined
      }
    },
    responseData: {
      type: String,
      default: function () {
        return undefined
      }
    },
    searchKeyword: {
      type: [String, String],
      default: function () {
        return 'keyword'
      }
    },
    showValueShow: {
      type: [Object, Array, String],
      default: function () {
        return []
      }
    }
  },
  computed: {
    customValue: {
      get: function () {
        if (!this.value || this.value.length === 0) {
          this.localValue = ''
        }
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    },
    tableColumn () {
      return this.initTableColum()
    }
  },
  data () {
    return {
      keyboardConfig: {
        isArrow: true
      },
      isfristsearch: 0,
      localValue: '',
      searchValue: '',
      suffixIcon: 'el-icon-arrow-down',
      isClose: true,
      loading4: false,
      tableData: [],
      localQueryValue: {},
      pagerValue: {
        pageSize: 100000,
        customPage: 1,
        total: 0
      },
      showPager: false,
      allTableData: [],
      parsentParms: '',
    }
  },
  // mounted () {
  //   this.getTableData()
  // },
  methods: {
    // 删除
    hidePanel () {
      if (!!this.searchValue) {
        this.searchValue = ''
        this.searchValueChange()
      }
      if (this.$refs.pan) {
        this.$nextTick(_ => {
          this.$refs.pan.blur()
        })
      }
    },
    // 添加enter时间
    enterSelect (event) {
      if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
        if (this.$refs.xGrid) {
          this.$refs.xGrid.focus()
        }
        let a = this.$refs.xGrid.getCurrentRecord()
        if (!a) {
          this.$nextTick(_ => {
            if (this.tableData.length > 0) {
              this.$refs.xGrid.setCurrentRow(this.tableData[0], this.tableColumn[0].field)
            }
          })
        } else {
          this.$refs.xGrid.setCurrentRow(a, this.tableColumn[0].field)
        }
      } else if (event.key === 'Enter') {
        let a = this.$refs.xGrid.getCurrentRecord()
        if (a) {
          this.cellClickEvent({row: a})
        }
      }
    },
    // 初始化
    // 初始化查询参数
    initQueryValue () {
      this.localQueryValue = Object.assign(this.localQueryValue, this.queryValue, {
        p: this.pagerValue.customPage,
        pageoffset: this.pagerValue.pageSize
      })
    },
    initShowLocalValue () {
      if (this.customValue && this.customValue.length > 0) {
        if (!this.localValue || this.localValue.length === 0) {
          if (this.multiple) {
            this.localValue = this.tableData.filter(it => this.customValue.some(it1 => it1 === it[this.clickValue])).map(it => it[this.showValue]).join(',')
            this.$emit('selectChange', this.tableData.filter(it => this.customValue.some(it1 => it1 === it[this.clickValue])))
          } else {
            if (Array.isArray(this.column)) {
              this.localValue = this.tableData.filter(it => this.customValue === it[this.clickValue]).map(it => it[column[0]]).join(',')
            } else {
              this.localValue = this.tableData.filter(it => this.customValue === it[this.clickValue]).map(it => it[column]).join(',')
            }
            this.$emit('selectChange', this.tableData.filter(it => this.customValue === it[this.clickValue]))
          }
        }
      }
    },
    // 计算表格例表
    initTableColum () {
      let a = []
      if (this.column) {
        if (Array.isArray(this.column)) {
          this.column.forEach(it => {
            let b = {}
            if (typeof it === 'string') {
              b = {
                field: it
              }
            } else {
              b = {
                field: it.field || '',
                title: it.title || '',
              }
            }
            a.push(b)
          })
        } else if (typeof this.column === 'string') {
          a.push({
            field: this.column || '',
          })
        } else {
          a.push({
            field: this.column.field || '',
          })
        }
      }
      return a
    },
    // 关键字
    // 搜索
    searchValueChange () {
      if (this.searchValue && this.searchValue.length > 0) {
        let a = this.allTableData.filter(it => it[this.showValue].indexOf(this.searchValue) >= 0)
        this.tableData = JSON.parse(JSON.stringify(a))
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.allTableData))
      }
      // this.pagerValue.customPage = 1
      // if (this.searchValue && this.searchValue.length > 0) {
      //   if (typeof this.searchKeyword === 'string') {
      //     this.localQueryValue[this.searchKeyword] = this.searchValue
      //   } else if (Array.isArray(this.searchKeyword)){
      //     this.searchKeyword.forEach(it => {
      //       this.localQueryValue[it] = this.searchValue
      //     })
      //   }
      // } else {
      //   if (typeof this.searchKeyword === 'string') {
      //     delete this.localQueryValue[this.searchKeyword]
      //   } else if (Array.isArray(this.searchKeyword)){
      //     this.searchKeyword.forEach(it => {
      //       delete this.localQueryValue[it]
      //     })
      //   }
      // }
      // 本地搜索 多条件搜索目前仅支持远端搜索
      // if (!this.showPager) {
      //   if (typeof this.searchKeyword === 'string') {
      //     if (this.localQueryValue[this.searchKeyword]) {
      //       let a = this.allTableData.filter(it => it[this.showValue].indexOf(this.localQueryValue[this.searchKeyword]) >= 0)
      //       this.tableData = JSON.parse(JSON.stringify(a))
      //     } else {
      //       let a = this.allTableData
      //       this.tableData = JSON.parse(JSON.stringify(a))
      //     }
      //   } else if (Array.isArray(this.searchKeyword)) {
      //     if (this.searchKeyword.some(it => this.localQueryValue.hasOwnProperty(it))) {
      //       // let a = this.allTableData.filter(it => {
      //       //
      //       // })
      //     } else {
      //       let a = this.allTableData
      //       this.tableData = JSON.parse(JSON.stringify(a))
      //     }
      //   }
      // } else {
        // 远端搜索
      // this.getTableData()
      // }
    },
    // 选中修改样式
    rowStyle ({ row, rowIndex }) {
      if (Array.isArray(this.customValue)) {
        if (this.value.some(it => it === row[this.clickValue])) {
          return {
            color: '#409eff'
          }
        }
      } else {
        if (row[this.clickValue] === this.customValue) {
          return {
            color: '#409eff'
          }
        }
      }
    },
    // 获取表格数据
    getTableData () {
      if (this.options && !this.api) {
        this.tableData = JSON.parse(JSON.stringify(this.options))
        this.pagerValue.total = this.tableData.length
        this.showPager = Number(this.tableData.length) > (this.tableData || []).length
        this.initSelectValue()
        if (!this.showPager) {
          this.allTableData = JSON.parse(JSON.stringify(this.tableData))
        }
      } else {
        if (!this.api || !this.getPage) return
        this.initQueryValue()
        this.loading4 = true
        this.api[this.getPage](this.localQueryValue).then((res) => {
          this.tableData = (res[this.responseData] || [])//Modules
          this.pagerValue.total = res.Total
          this.showPager = Number(res.Total) > (this.tableData || []).length
          this.initSelectValue()
          if (!this.showPager) {
            this.allTableData = JSON.parse(JSON.stringify(this.tableData))
          }
        }).finally(() => {
          this.loading4 = false
        })
      }
    },
    // 默认选中
    initSelectValue () {
      if (!this.tableData) return
      if (!this.value || this.value === '') return
      if (this.multiple) {
        let l = (this.customValue || []).filter(it => {
          this.tableData.some(it1 => it1[this.clickValue] === it)
        })
        let r = (this.customValue || []).filter(it => {
          !this.tableData.some(it1 => it1[this.clickValue] === it)
        })
        let ll = []
        if (l.length > 0) {
          ll = (this.tableData || []).filter(it => (this.customValue || []).some(it1 => it1 === it[this.clickValue])).map(it => it[this.showValue])
        } else {
          let a = (this.showValueShow || []).filter(it => r.some(it1 => it.clickValue === it1.clickValue))
          ll.push(...(a.map(it => it[this.showValue])))
          this.tableData.push(...a)
        }
        if (ll.length > 0) {
          this.localValue = ll.join(',')
        }
      } else {
        let a = (this.tableData || []).filter(it => it[this.clickValue] === this.customValue)
        if (a.length > 0) {
          this.localValue = a[0][this.showValue]
        } else {
          if (this.showValueShow.length > 0) {
            this.tableData.push(this.showValueShow)
            this.localValue = this.showValueShow[this.showValue]
          }
        }
      }
    },
    // 单元格点击事件
    cellClickEvent ({ row }) {
      if (this.multiple) {
        this.localValue = this.localValue || ''
        this.$nextTick(_ => {
          let a = (this.customValue || []).indexOf(row[this.clickValue])
          if (a >= 0) {
            this.customValue.splice(a, 1)
          } else {
            if (this.customValue) {
              this.customValue.push(row[this.clickValue])
            } else {
              this.customValue = [row[this.clickValue]]
            }
          }
          this.$nextTick(_ => {
            // this.localValue = this.tableData.filter(it => this.customValue.some(it1 => it1 === it[this.clickValue])).map(it => it[this.showValue]).join(',')
            this.$emit('selectChange', this.tableData.filter(it => this.customValue.some(it1 => it1 === it[this.clickValue])))
          })
        })
      } else {
        this.customValue = row[this.clickValue]
        // this.localValue = row[this.showValue]
        this.$emit('selectChange', [row])
        this.$refs.xDown.togglePanel()
      }
    },
    // 点击后面的图标
    suffixClick () {
      if (this.suffixIcon === 'el-icon-circle-close') {
        this.customValue = undefined
        this.localValue = ''
        this.$emit('selectChange', [])
      } else {
        this.$refs.xDown.togglePanel()
      }
    },
    // 聚焦
    focusEvent () {
      if (this.isClose) {
        this.isClose = false
      }
      if (!this.$refs.xDown.visiblePanel) {
        this.suffixIcon = 'el-icon-arrow-up'
        this.$refs.xDown.showPanel()
        this.$nextTick(_ => {
          if (this.$refs.searchValue) {
            this.$refs.searchValue.focus()
          }
          this.$nextTick(_ => {
            if (this.$refs.xGrid) {
              this.$refs.xGrid.focus()
            }
            this.$refs.dropdown.addEventListener('keyup', this.enterSelect, true)
          })
        })
      } else {
        this.suffixIcon = 'el-icon-arrow-down'
        this.$refs.xDown.hidePanel()
        if (this.$refs.pan) {
          this.$nextTick(_ => {
            this.$refs.pan.blur()
            this.$nextTick(_ => {
              this.$refs.dropdown.removeEventListener('keyup', this.enterSelect)
            })
          })
        }
      }
      // this.$refs.xDown.togglePanel()
    },
    blurEvent () {
      if (!this.isClose) {
        this.isClose = true
      }
      this.suffixIcon = 'el-icon-arrow-down'
    },
    // 自定义删除
    inputChange () {
      this.mouseover()
    },
    // 鼠标移入
    mouseover () {
      if (this.isClose) {
        if (this.customValue && this.customValue.length > 0) {
          this.suffixIcon = 'el-icon-circle-close'
        }
      }
    },
    // 移除
    mouseout () {
      if (this.isClose) {
        this.suffixIcon = 'el-icon-arrow-down'
      }
    },
    // 全选
    allClick () {
      this.customValue = this.tableData.map(it => it[this.clickValue])
      // this.localValue = this.tableData.map(it => it[this.showValue]).join(',')
      this.$emit('selectChange', this.tableData)
    },
    // 取消全选
    cancelClick () {
      this.customValue = []
      this.$emit('selectChange', [])
    },
    // 上页下页
    jumpPage (value) {
      this.pagerValue.customPage = value
      this.getTableData()
    },
    // 页数改变
    sizeChange (value) {
      this.pagerValue.pageSize = value
      this.getTableData()
    },
  },
  watch: {
    customValue (n, o) {
      if (!!n && n.length > 0) {
        let a = []
        if (this.multiple) {
          a = (this.allTableData || []).filter(it => {
            return (n || []).some(it1 => it[this.clickValue] === it1)
          })
        } else {
          a = this.allTableData.filter(it => it[this.clickValue] === n)
        }
        this.localValue = a.map(it => it[this.showValue]).join(',')
      } else {
        this.localValue = ''
      }
    },
    queryValue: {
      deep: true,
      immediate: true,
      handler (n, o) {
        if (JSON.stringify(n) !== this.parsentParms) {
          this.initQueryValue()
          this.getTableData()
          this.parsentParms = JSON.stringify(n)
        }
      }
    }
  }
}
</script>

<style scoped>
  .my-dropdown {
    background-color: #FFFFFF;
    padding: 10px 0 10px 10px;
    box-shadow:    0 -1px 0 0 rgba(0,0,0,.5),   /*上边阴影*/
                    -1px 0 0 0 rgba(0,0,0,.5),   /*左边阴影*/
                    1px 0 0 0 rgba(0,0,0,.5),    /*右边阴影*/
                    0 1px 0 0 rgba(0,0,0,.5);    /*下边阴影*/
  }
  .tableClass >>> .vxe-body--column{
    height: 24px;
    padding: 5px 0;
  }
  .tableClass >>> .vxe-body--column:hover{
    cursor: pointer;
  }
  .tableClass >>> .vxe-table--body {
    min-width: 150px;
  }
  .tableClass >>> .vxe-cell {
    width: 100% !important;
  }
</style>
